<?php

/*
  Project     : 48c6c450f1a4a0cc53d9585dc0fee742
  Created on  : Mar 16, 2013, 11:29:15 PM
  Author      : Truong Khuong - khuongxuantruong@gmail.com
  Description :
  Purpose of the stylesheet follows.
 */

class auth_backend extends CI_Module {

    public $controller;
    public $auth_login_uri;
    public $privilege = -1;

    function __construct() {
        parent::__construct();
        $this->load->model("backend/auth_model");
        $this->controller = $this->router->fetch_class();
        $this->auth_login_uri = site_url("cms/auth/login") . '?state=' . uri_string();
        $this->access_denied_uri = site_url("cms/auth/denied") . '?state=' . uri_string();
        $this->isAjax = $this->input->is_ajax_request();
    }

    function login() {
        //$this->check_oauth();
        if (!isset($_SESSION["auth"]["user"])) {
            if ($this->isAjax) {
                if ($this->input->get_post('ajaxtype') === 'json') {
                    $R["result"] = -903;
                    $R["message"] = ("You must be login.");
                    die(json_encode($R));
                } else {
                    die("You must be login.");
                }
            } else {
                redirect($this->auth_login_uri); //die("You must be login.");
            }
        }
        return $this;
    }
	function checkoauth(){
        if(isset($_SESSION['frontend']['User']) && !empty($_SESSION['frontend']['User'])){
            $_username=$_SESSION['frontend']['User']['UserName'];
            $_SESSION["auth"]["user"]=new stdClass();
            $_SESSION["auth"]["user"]->ause_name=$_username;
            
            $user = $this->auth_model->getuser("$_username");
            if ($user != null) {
                if ($user->ause_status === "true") {
                    unset($user->ause_password);
                    $_SESSION["auth"]["user"] = $user;
                    $privileges = array();
                    $_SESSION["auth"]["privileges"] = $privileges;
                    @$this->fileverify();

                }else {
                    redirect($this->access_denied_uri);
                }
            }else{
                redirect($this->access_denied_uri);
            }
        }
    }
    function check_login() {
        $_password = $this->input->post("password");
        $_username = $this->input->post("username");
        $R["result"] = -998;
        $R["message"] = ("Access is denied - Request invalid.");
        if (isset($_SESSION["auth"]["user"])) {
            $R["result"] = 1;
            $R["message"] = ("Valid login.");
            //} elseif (!isset($_SESSION['auth']['oauth'])) {
            //    $R["result"] = -991;
            //    $R["message"] = ascii_to_entities("Authorized API Access, OAuth don't allow.");
            //    goto result;
        } elseif ($_password != false && $_username != false) {

            if (!isset($_SESSION["logintry"]))
                $_SESSION["logintry"] = 0;
            $_SESSION["logintry"]++;
            if ($_SESSION["logintry"] > 3) {
                if (!isset($_SESSION["logintrytime"]))
                    $_SESSION["logintrytime"] = time();
                $timedelay = 60 * 15 - (time("now") - $_SESSION["logintrytime"]);
                if ($timedelay <= 0) {
                    $_SESSION["logintry"] = 0;
                    unset($_SESSION["logintrytime"]);
                } else {
                    $p = floor($timedelay / 60);
                    $p = $p > 0 ? "$p minute " : "";
                    $s = $timedelay % 60;
                    $R["result"] = -999;
                    $R["message"] = ("[Access Denied] Sorry, there have been more than 5 failed login<br/>attempts for this account.<br/>
						It is temporarily blocked in 15 minutes.<br/>
						Remaining time : $p$s second.
						");
                    return $R;
                }
            }


            //$_username = $_SESSION['auth']['oauth']['email'];
            $_name = $_username; //$_SESSION['auth']['oauth']['name'];
            $user = $this->auth_model->getuser("$_username");
            if ($user != null) {
                if ($user->ause_password != md5($_username . $_password . $user->ause_secretkey)) {
                    $_name = $user->ause_name;
                    $R["result"] = -906;
                    $R["message"] = ("Login failed for user '$_name'.");
                    return $R;
                }
                if ($user->ause_delete !== null) {
                    $R["result"] = -901;
                    $R["message"] = ("Valid login but user have been deleted.");
                    return $R;
                }
                if ($user->ause_status === "true") {
                    unset($user->ause_password);
                    //unset($user->ause_salt);
                    //unset($user->ause_secretkey);
                    $_SESSION["auth"]["user"] = $user;
                    //$this->session->set_userdata('auth', $_SESSION["auth"]);
                    //$tmp = @$this->auth_model->getprivileges($user->ause_id);
                    $privileges = array();
                    if (!empty($tmp))
                        foreach ($tmp as $pve) {
                            $privileges[$pve->apri_key] = $pve;
                        }
                    $_SESSION["auth"]["privileges"] = $privileges;
                    @$this->fileverify();
                    $R["result"] = 1;
                    $R["message"] = ("Valid login.");
                    $_SESSION["logintry"] = 0;
                } else {
                    $R["result"] = -902;
                    $R["message"] = ("Valid login but user is not active.");
                    return $R;
                }
            } else {
                $R["result"] = -904;
                $R["message"] = ("User does't exist or invalid user.");
                return $R;
            }
        }
        return $R;
    }

    function verify() {
        
    }

    function crypt() {
        
    }

    function fileverify() {
        unset($_SESSION['KCFINDER']);
        //if($_SESSION["auth"]["privileges"]['filemanage']->aupr_permission==777){
        if (
                $_SESSION["auth"]["user"]->ause_authority == 'Administrator' ||
                $_SESSION["auth"]["user"]->ause_authority == 'Admin' ||
                $_SESSION["auth"]["user"]->ause_authority == 'User'
        ) {
            $_SESSION['KCFINDER']['disabled'] = false;
            $_SESSION['KCFINDER']['uploadURL'] = ('/data');
            $_SESSION['KCFINDER']['uploadDir'] = '../../data';
                $files = array(
                    'upload' => true,
                    'delete' => true,
                    'copy' => true,
                    'move' => true,
                    'rename' => true
                );
                $dirs = array(
                    'create' => true,
                    'delete' => true,
                    'rename' => true
                );
            

            //}elseif($_SESSION["auth"]["privileges"]['filemanage']->aupr_permission>0){
        } elseif ($_SESSION["auth"]["user"]->ause_authority == 'View') {
            $_SESSION['KCFINDER']['uploadURL'] = ('/data'); //base_url("data");
            $_SESSION['KCFINDER']['uploadDir'] = '../../data';
            $_SESSION['KCFINDER']['disabled'] = false;
            
                $files = array(
                    'upload' => false,
                    'delete' => false,
                    'copy' => false,
                    'move' => false,
                    'rename' => false
                );
                $dirs = array(
                    'create' => false,
                    'delete' => false,
                    'rename' => false
                );
            
        } else {
            $_SESSION['KCFINDER']['uploadURL'] = base_url('data'); //base_url("data");
            $_SESSION['KCFINDER']['uploadDir'] = '../../data';
            $_SESSION['KCFINDER']['disabled'] = true;
            $files = array(
                'upload' => false,
                'delete' => false,
                'copy' => false,
                'move' => false,
                'rename' => false
            );
            $dirs = array(
                'create' => false,
                'delete' => false,
                'rename' => false
            );
            
        }
        $_SESSION['KCFINDER']['access']=array(
                    'files' => $files,
                    'dirs' => $dirs
        );
        
    }

    function privilege() {

        if (
                $_SESSION["auth"]["user"]->ause_authority == 'Administrator' ||
                $_SESSION["auth"]["user"]->ause_authority == 'Admin' ||
                $_SESSION["auth"]["user"]->ause_authority == 'User'
        ) {
            $this->privilege = (object) array(
                        'apri_name' => '',
                        'apri_key' => ''
            );
            $this->privilege->aupr_permission = 777;
            return $this;
        } elseif ($_SESSION["auth"]["user"]->ause_authority == 'View') {
            $this->privilege = (object) array(
                        'apri_name' => '',
                        'apri_key' => ''
            );
            $this->privilege->aupr_permission = 755;
            return $this;
        }
        if (isset($_SESSION["auth"]["privileges"])) {
            $privileges = $_SESSION["auth"]["privileges"];
            if (isset($privileges[$this->controller])) {
                $this->privilege = $privileges[$this->controller];
                if ($this->privilege->aupr_permission != 0)
                    if ($_SESSION["auth"]['user']->ause_position >= $this->privilege->apri_position)
                        return $this;
            }
        }
        if ($this->isAjax) {
            $R["result"] = -903;
            $R["message"] = (
                    "Access is denied for user \"" . $_SESSION["auth"]["user"]->ause_name . "\".<br/>
                    This function to requires an administrative account.<br/>
                    Please check your authority, and try again."
            );
            if ($this->input->get_post('ajaxtype') === 'json') {
                die(json_encode($R));
            } else {
                die($R["message"]);
            }
        } else {
            redirect($this->access_denied_uri); //echo("Access denied.");
        }
    }

}

?>
